#include "wtl.h"
#include "..\..\ProcessHistory\PHScroll.h"
#include "..\screen.h"
#include "..\resource.h"
#include "..\PH.h"

extern PHDisplay phd;
extern PH ph_instance;
using namespace std;

LRESULT PHScroll::OnRB(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
	int x=GET_X_LPARAM(lParam);
	int y=GET_Y_LPARAM(lParam);

	POINT pt;
	pt.x=x;
	pt.y=y;
	PHDToL(pt);
	/*Previously selected*/
	map<long,RECT>::iterator sit=phd._ProcessAreas.find(phd._selected);
	if(sit!=phd._ProcessAreas.end())
	{
		RECT r=sit->second;
		PHLToD(r);
		InvalidateRect(&r);
	}
	
	for(map<long,RECT>::iterator it=phd._ProcessAreas.begin();
		it!=phd._ProcessAreas.end();it++)
	{
		if(PtInRect(&it->second,pt))
		{
			phd._selected=it->first;
			RECT r=it->second;
			PHLToD(r);
			InvalidateRect(&r);
			CMenu menu;
			menu.LoadMenu( IDR_CONTEXT_MENU);
			CMenuHandle mh=menu.GetSubMenu(0);
			// convert to point clicked to screen coordinates/ hwnd needs to handle message
			POINT menupt;
			menupt.x=x;
			menupt.y=y;
			ClientToScreen(&menupt);
			TrackPopupMenu((HMENU)mh, TPM_LEFTALIGN, 
				menupt.x, menupt.y,0, ph_instance._hWnd,NULL);
			return TRUE;
		}
	}
	phd._selected=0;
	return TRUE;
}
//LRESULT PHScroll::OnLB(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
//{
	//FindHAOnScreen(GET_X_LPARAM(lParam),GET_Y_LPARAM(lParam));
//	return TRUE;
//}

void PHScroll::SetSize(SIZE m_size)
{		
	SetScrollOffset(0, 0, FALSE);
	SetScrollSize(m_size);
}

void PHScroll::PHLToD(RECT &r)
{	
		/*translate pts*/
	//only microsoft could create this coordinate system
	CWindowDC dc(m_hWnd);
	dc.SetMapMode(MM_TEXT);
	dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y);
	dc.SetViewportExt(m_sizeAll);
	dc.LPtoDP(&r);
}

void PHScroll::PHDToL(POINT &p)
{
		/*translate pts*/
	//only microsoft could create this coordinate system
	CWindowDC dc(m_hWnd);
	dc.SetMapMode(MM_TEXT);
	dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y);
	dc.SetViewportExt(m_sizeAll);
	dc.DPtoLP(&p);
}

#include "../Query.h"
#include <boost\thread\thread.hpp>
using namespace boost::posix_time;
extern ptime wr,wl;
extern void RF1(string where);
extern PHQuery phq;
extern boost::mutex work_mtx;

LRESULT PHScroll::OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
	wr=phd._WinRight,wl=phd._WinLeft;
		switch(wParam)
		{
	
		case VK_RIGHT:
		{
			string where=phq.Construct(phd._WinRight);
			work_mtx.lock();
			RF1(where);
		}
		break;
		case VK_LEFT:
		{
			work_mtx.lock();
			time_duration td=phd._WinRight-phd._WinLeft;
			string where=phq.Construct(phd._WinLeft-td);
			RF1(where);
		}//case VK_LEFT
		}//switch vKey
	return true;
}
